package com.cloudbroker.bcs.platform.ltb.middle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.CombDetailResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.CombDetailForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.CombDetailQryBackVo;
import com.cloudbroker.bcs.csvc.push.api.vo.request.*;
import com.cloudbroker.bcs.csvc.push.api.vo.response.PushBack;
import com.cloudbroker.bcs.csvc.push.api.vo.response.PushReportBack;
import com.cloudbroker.bcs.csvc.push.api.vo.response.TagAliasBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.PushBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.vo.XinanPushForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.back.RegisterBackForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.back.TagsAddBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.back.TagsRemoveBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.NotifyForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.RegisterForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.TagsAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.TagsRemoveForm;
import com.cloudbroker.bcs.platform.ltb.common.marketUtil.util.HttpClientUtil;
import com.cloudbroker.bcs.platform.ltb.middle.entity.*;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.PushListParam;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.push.PushExtService;
import com.cloudbroker.bcs.platform.ltb.middle.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by daibd19671 on 2016/9/8.
 */
@Service
public class PushServiceImpl implements PushService {

    @Resource
    private AppUserService appUserService;
    @Resource
    private AppUserTagService appUserTagService;
    @Resource
    private PushMsgService pushMsgService;
    @Resource
    private PushListService pushListService;

    @Resource
    private PushExtService pushExtService;
    @Resource
    private UserService userService;
    @Resource
    private MsgService msgService;
    @Resource
    private UserRemindService userRemindService;
    @Resource
    private LedT2Service ledT2Service;

    private Logger logger = Logger.getLogger(PushServiceImpl.class);



    @Override
    public PushList getPushList(PushList pushList) {
        return pushListService.getPushList(pushList);
    }

    @Override
    public void updatePushList(PushList pushList) {
        pushListService.updatePushList(pushList);
    }


    @Override
    public List<PushList> selectPushList(PushListParam pushList) {
        return pushListService.selectPushList(pushList);
    }

    @Override
    public Integer countPushList(PushListParam param) {
        return pushListService.countPushList(param);
    }

    private String tagListToString(List<AppUserTags> list){
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for(AppUserTags tag : list){
            sb.append(tag.getTag());
            if(i!=list.size()){
                sb.append(",");
            }
            i++;
        }
        return sb.toString();
    }
    /**
     * 设置极光registration_id--848540
     * APP登录精英汇时调用，无记录则添加
     * registration_id或者App_user_id 不同，更新registration_id，更新精英汇和极光服务器绑定的Alias、Tag
     */
    @Override
    public RegisterBackForm registrationIdMgr(RegisterForm registerForm) {
        AppUser appUser = new AppUser(registerForm.getUser().getUser_id(), registerForm.getRegistration_id(), registerForm.getCompany_id(), registerForm.getSendercomp_id(), registerForm.getAlias_name());
        // 查询用户对应registration_id
        AppUser user = this.queryUser(registerForm.getUser().getUser_id(), registerForm.getCompany_id(), appUser.getSendercomp_id());
        if (user == null) {
            // 新用户注册 添加绑定记录
            appUserService.addAppUser(appUser);
            user = new AppUser();
            user.setRegistration_id(registerForm.getRegistration_id());
            user.setTerminal_type(registerForm.getTerminal_type());
            user.setCompany_id(registerForm.getCompany_id());
            user.setSendercomp_id(registerForm.getSendercomp_id());
            user.setAlias_name(registerForm.getAlias_name());
            user.setApp_user_id(registerForm.getUser().getUser_id());
        }else{
            if(StringUtils.isEmpty(user.getAlias_name())){
                user.setAlias_name(registerForm.getAlias_name());
                appUserService.updateAppUserAlias(user);
            }
        }
        PushMsg pushMsg = this.getPushMsg(registerForm.getCompany_id(), registerForm.getSendercomp_id());
        if(pushMsg== null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_MSG_ERR,RegisterBackForm.class);
        }
        // APP登录支持将精英汇标签绑定信息向极光同步
//        String tags_add = this.queryTagsByUserId(appUser);
        List<AppUserTags> tagAddList = this.queryTagsByUserId(appUser);
        String tags_add = this.tagListToString(tagAddList);
        // 判断registration_id 是否相同
        if (appUser.getRegistration_id().equals(user.getRegistration_id())) {
            if (tagAddList != null && tagAddList.size() > 0) {
                // 查询极光绑定信息，删除极光多余绑定信息
                DeviceTagAliasVo dta = new DeviceTagAliasVo();
                dta.setApp_key(pushMsg.getApp_key());
                dta.setApp_secret(pushMsg.getApp_secret());
                dta.setRegistration_id(appUser.getRegistration_id());
                TagAliasBack tagBack = pushExtService.getDeviceTagAlias(dta);
                if (!VOUtil.isSuccess(tagBack)) {
                    logger.error("======更新tag  别名======");
                    logger.error(tagBack.toString());
                    return VOUtil.genErrorResult(tagBack.getError_no(),tagBack.getError_info(),
                            RegisterBackForm.class);
                }
                UpdateDeviceTagAliasVo udta = new UpdateDeviceTagAliasVo();
                udta.setRegistration_id(appUser.getRegistration_id());
                udta.setApp_key(pushMsg.getApp_key());
                udta.setApp_secret(pushMsg.getApp_secret());
                udta.setAlias_name(appUser.getAlias_name().trim());
                udta.setTags_add(tags_add);
                udta.setTags_remove(tagBack.getTags());
                HSBCPSBackVO result = pushExtService.updateDeviceTagAlias(udta);
                if (!VOUtil.isSuccess(result)) {
                    logger.error("======重新绑定tag  别名======");
                    logger.error(result.toString());
                    return VOUtil.genErrorResult(result.getError_no(),result.getError_info(),
                            RegisterBackForm.class);
                }
            }
        }else {
            // 不同，进行registrationId、Alias、Tag更新（绑定新的registrationId）
            HSBCPSBackVO result = this.updateAliasAndTag(user, appUser.getRegistration_id(), appUser.getTerminal_type(),pushMsg,tags_add);
            if (!VOUtil.isSuccess(result)) {
                logger.error("======更新tag  别名======");
                logger.error(result.toString());
                return VOUtil.genErrorResult(result.getError_no(),result.getError_info(),
                        RegisterBackForm.class);
            }
        }
        return VOUtil.setSuccessResult(new RegisterBackForm());
    }



    /**
     * 设置Tag-添加tag绑定--848541
     */
    @Override
    public TagsAddBackVo tagsAdd(TagsAddForm tagsAddForm) {
        AppUser appUser = this.queryUser(tagsAddForm.getUser_id(), tagsAddForm.getCompany_id(), tagsAddForm.getSendercomp_id());
        if(appUser == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.APP_USER_NOT_EXIST,
                    TagsAddBackVo.class);
        }
        Set<String> tagSet = new HashSet<>();
        List<AppUserTags> list = this.queryTagsByUserId(appUser);
        String tagStr = this.tagListToString(list);
        String[] tags = tagStr.split(",");
        for(String t : tags){
            if(StringUtils.isNotEmpty(t)){
                tagSet.add(t);
            }
        }
        //已经存在tag  则不保存
        if(tagSet.contains(tagsAddForm.getTag())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.TAG_EXIST,
                    TagsAddBackVo.class);
        }
        PushMsg pushMsg = this.getPushMsg(tagsAddForm.getCompany_id(),tagsAddForm.getSendercomp_id());
        if(pushMsg== null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_MSG_ERR,TagsAddBackVo.class);
        }
//		//调用极光服务器 设置tag接口-为tag添加设备
        AddRemoveTagVo addRemoveTagVo = new AddRemoveTagVo();
        addRemoveTagVo.setApp_key(pushMsg.getApp_key());
        addRemoveTagVo.setApp_secret(pushMsg.getApp_secret());
        addRemoveTagVo.setAddRegIds(appUser.getRegistration_id());
        addRemoveTagVo.setRemoveRegIds(null);
        addRemoveTagVo.setTag(tagsAddForm.getTag());
        HSBCPSBackVO result = pushExtService.addRemoveDevicesFromTag(addRemoveTagVo);
        if (VOUtil.isSuccess(result)) {
            // 设置消息平台 tag绑定关系
            this.setTag(tagsAddForm.getUser_id(), tagsAddForm.getTag(), "1",
                    tagsAddForm.getCompany_id(), tagsAddForm.getSendercomp_id());
        } else {
            logger.error("======添加标签失败======");
            logger.error(result.toString());
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.ADD_TAG_ERR, result.getError_info(),
                    TagsAddBackVo.class);
        }
        return VOUtil.setSuccessResult(new TagsAddBackVo());
    }

    /**
     * 设置Tag-删除tag绑定--848542
     */
    @Override
    public TagsRemoveBackVo tagsDelete(TagsRemoveForm tagsRemoveForm) {
        PushMsg pushMsg = this.getPushMsg(tagsRemoveForm.getCompany_id(),tagsRemoveForm.getSendercomp_id());
        if(pushMsg== null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_MSG_ERR,TagsRemoveBackVo.class);
        }
        AppUser appUser = this.queryUser(tagsRemoveForm.getUser_id(), tagsRemoveForm.getCompany_id(), tagsRemoveForm.getSendercomp_id());
        if(appUser == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.APP_USER_NOT_EXIST,
                    TagsRemoveBackVo.class);
        }
        // 调用极光服务器 设置tag接口-为tag删除设备
        AddRemoveTagVo addRemoveTagVo = new AddRemoveTagVo();
        addRemoveTagVo.setApp_key(pushMsg.getApp_key());
        addRemoveTagVo.setApp_secret(pushMsg.getApp_secret());
        addRemoveTagVo.setAddRegIds(null);
        addRemoveTagVo.setRemoveRegIds(appUser.getRegistration_id());
        addRemoveTagVo.setTag(tagsRemoveForm.getTag());
        HSBCPSBackVO result = pushExtService.addRemoveDevicesFromTag(addRemoveTagVo);
        if (VOUtil.isSuccess(result)) {
            // 设置消息平台 tag绑定关系
            this.setTag(tagsRemoveForm.getUser_id(),
                    tagsRemoveForm.getTag(), "3", tagsRemoveForm.getCompany_id(), tagsRemoveForm.getSendercomp_id());
        } else {
            logger.error("======删除标签失败======");
            logger.error(result.toString());
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.REM_TAG_ERR,result.getError_info(),
                    TagsRemoveBackVo.class);
        }
        return VOUtil.setSuccessResult(new TagsRemoveBackVo());
    }

	/**
     * 发送推送消息
     *  title 标题
     *  msgContent 通知内容
     *  tag 标签
     */
	@Override
	public PushBackVo sendPush(NotifyForm notifyForm) {
        PushMsg temp= new PushMsg();
        temp.setCompany_id(notifyForm.getCompany_id());
        temp.setSendercomp_id(notifyForm.getSendercomp_id());
        PushMsg pushMsg = pushMsgService.getPushMsg(temp);
        if(pushMsg== null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_MSG_ERR,PushBackVo.class);
        }
        PushBack back = null;
        String mobile = "";
        String alias_name = "";
        String tag = "";
        Long user_id = null;
        //批量导入excel推送
        if(StringUtils.isNotEmpty(notifyForm.getSend_mobile_list())){
            tag = notifyForm.getMessage_title()+System.currentTimeMillis();
            StringBuilder addSb = new StringBuilder();
            //====1====根据用户电话查询用户reg_id
            String[] mobiles = notifyForm.getSend_mobile_list().split(",");
            for(String mobile_str : mobiles){
                UserEntity userEntity = new UserEntity();
                userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                notifyForm.setUser_id(null);
                userEntity.setUser_name(mobile_str);
                userEntity.setSendercomp_id(notifyForm.getSendercomp_id());
                userEntity.setCompany_id(notifyForm.getCompany_id());
                UserEntity queryUser = userService.getUserEntity(userEntity);
                if(queryUser == null){
                    continue;
                }
                AppUser temp_appuser = new AppUser();
                temp_appuser.setApp_user_id(queryUser.getUser_id());
                temp_appuser.setCompany_id(queryUser.getCompany_id());
                temp_appuser.setSendercomp_id(queryUser.getSendercomp_id());
                AppUser appUser = appUserService.getAppUser(temp_appuser);
                if(appUser == null){
                    continue;
                }
                addSb.append(appUser.getRegistration_id());
                addSb.append(",");
                this.setTag(queryUser.getUser_id(),tag,"1",notifyForm.getCompany_id(),notifyForm.getCompany_id());
            }
            if(StringUtils.isEmpty(addSb.toString())) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_EXCEL_USER_ERR, PushBackVo.class);
            }
            String addIds = addSb.toString().substring(0,addSb.toString().length()-1);
            //====2====设置标签
            AddRemoveTagVo addRemoveTagVo = new AddRemoveTagVo();
            addRemoveTagVo.setApp_key(pushMsg.getApp_key());
            addRemoveTagVo.setApp_secret(pushMsg.getApp_secret());
            addRemoveTagVo.setTag(tag);
            addRemoveTagVo.setAddRegIds(addIds);
            HSBCPSBackVO addBack = pushExtService.addRemoveDevicesFromTag(addRemoveTagVo);
            if(!VOUtil.isSuccess(addBack)){
                return VOUtil.genErrorResult(addBack.getError_no(), addBack.getError_info(), PushBackVo.class);
            }
            //====3====按标签推送
            PushTagVo tagVo = new PushTagVo();
            tagVo.setApp_key(pushMsg.getApp_key());
            tagVo.setApp_secret(pushMsg.getApp_secret());
            tagVo.setMessage_title(notifyForm.getMessage_title());
            tagVo.setContent(notifyForm.getContent());
            tagVo.setTag(tag);
            tagVo.setPush_time(notifyForm.getPush_time());
            back = pushExtService.sendAllNotificationWithTag(tagVo);
            if(!VOUtil.isSuccess(back)){
                return VOUtil.genErrorResult(back.getError_no(), back.getError_info(), PushBackVo.class);
            }
            //====4====删除标签
//            addRemoveTagVo = new AddRemoveTagVo();
//            addRemoveTagVo.setApp_key(msg.getApp_key());
//            addRemoveTagVo.setApp_secret(msg.getApp_secret());
//            addRemoveTagVo.setTag(notifyForm.getMessage_title());
//            addRemoveTagVo.setRemoveRegIds(addIds);
//            HSBCPSBackVO remBack = pushExtService.addRemoveDevicesFromTag(addRemoveTagVo);
//            if(!VOUtil.isSuccess(remBack)){
//                return VOUtil.genErrorResult(remBack.getError_no(), remBack.getError_info(), PushBackVo.class);
//            }
            //返回成功信息
        }else {
            if (PushType.TAG.getVal().equals(notifyForm.getPush_type())) {
                // 按标签推送
                PushTagVo tagVo = new PushTagVo();
                tagVo.setApp_key(pushMsg.getApp_key());
                tagVo.setApp_secret(pushMsg.getApp_secret());
                tagVo.setMessage_title(notifyForm.getMessage_title());
                tagVo.setContent(notifyForm.getContent());
                tagVo.setTag(notifyForm.getTag());
                tagVo.setPush_time(notifyForm.getPush_time());
                back = pushExtService.sendAllNotificationWithTag(tagVo);
                tag = notifyForm.getTag();
            } else if (PushType.ALIAS.getVal().equals(notifyForm.getPush_type())) {
                // 按别名推送
                PushAliasVo pushAliasVo = new PushAliasVo();
                pushAliasVo.setApp_key(pushMsg.getApp_key());
                pushAliasVo.setApp_secret(pushMsg.getApp_secret());
                pushAliasVo.setMessage_title(notifyForm.getMessage_title());
                pushAliasVo.setContent(notifyForm.getContent());
                pushAliasVo.setAlias_name(notifyForm.getAlias_name());
                pushAliasVo.setPush_time(notifyForm.getPush_time());
                alias_name = notifyForm.getAlias_name();
                back = pushExtService.sendAllNotificationWithAlias(pushAliasVo);
            } else if (PushType.REGISTRATION_ID.getVal().equals(notifyForm.getPush_type())) {
                // 按设备编号推送
                UserEntity userEntity = new UserEntity();
                userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                notifyForm.setUser_id(null);
                userEntity.setUser_name(notifyForm.getMobile());
                userEntity.setSendercomp_id(notifyForm.getSendercomp_id());
                userEntity.setCompany_id(notifyForm.getCompany_id());
                UserEntity queryUser = userService.getUserEntity(userEntity);
                if (queryUser == null) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT, PushBackVo.class);
                }
                AppUser appUserTemp = new AppUser(queryUser.getUser_id(), queryUser.getCompany_id(), queryUser.getSendercomp_id());
                AppUser appUser = appUserService.getAppUser(appUserTemp);
                if (appUser == null) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_REGID_ERR, PushBackVo.class);
                }
                PushRegIdVo pushRegIdVo = new PushRegIdVo();
                pushRegIdVo.setRegistration_id(appUser.getRegistration_id());
                pushRegIdVo.setApp_key(pushMsg.getApp_key());
                pushRegIdVo.setApp_secret(pushMsg.getApp_secret());
                pushRegIdVo.setMessage_title(notifyForm.getMessage_title());
                pushRegIdVo.setContent(notifyForm.getContent());
                pushRegIdVo.setPush_time(notifyForm.getPush_time());
                back = pushExtService.sendAllNotificationWithRegId(pushRegIdVo);
                mobile = queryUser.getMobile();
                user_id = queryUser.getUser_id();
            } else if (PushType.ALL.getVal().equals(notifyForm.getPush_type())) {
                // 推送所有-广播
                PushAllVo pushAllVo = new PushAllVo();
                pushAllVo.setApp_key(pushMsg.getApp_key());
                pushAllVo.setApp_secret(pushMsg.getApp_secret());
                pushAllVo.setMessage_title(notifyForm.getMessage_title());
                pushAllVo.setContent(notifyForm.getContent());
                pushAllVo.setPush_time(notifyForm.getPush_time());
                back = pushExtService.sendNotificationAll(pushAllVo);
            } else {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_TYPE_ERR, PushBackVo.class);
            }
            boolean result = back == null ? false : VOUtil.isSuccess(back);
            if (!result) {
                return VOUtil.genErrorResult(back.getError_no(), back.getError_info(), PushBackVo.class);
            }
        }
        //记录推送表
        PushList pushList = new PushList();
        pushList.setContent(notifyForm.getContent());
        pushList.setMessage_title(notifyForm.getMessage_title());
        pushList.setCreate_time(new Date().getTime());
        pushList.setPush_type(notifyForm.getPush_type());
        pushList.setCompany_id(notifyForm.getCompany_id());
        pushList.setSendercomp_id(notifyForm.getSendercomp_id());
        pushList.setMobile(mobile);
        pushList.setUser_id(user_id);
        pushList.setAlias_name(alias_name);
        pushList.setTag(tag);
        pushList.setPush_time(notifyForm.getPush_time());
        pushList.setPush_status("1");
        pushList.setJpush_id(back.getMsg_id());
        pushList.setAdmin_id(notifyForm.getAdmin_id());
        pushList.setAdmin_name(notifyForm.getAdmin_name());
        pushList.setMsg_type(notifyForm.getMsg_type());
        pushListService.addPushList(pushList);

        //记录消息表
        Msg msg = new Msg();
        if (StringUtils.isNotEmpty(notifyForm.getMobile())) {
            UserEntity userEntity = new UserEntity();
            userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            userEntity.setUser_name(notifyForm.getMobile());
            userEntity.setSendercomp_id(notifyForm.getSendercomp_id());
            userEntity.setCompany_id(notifyForm.getCompany_id());
            UserEntity queryUser = userService.getUserEntity(userEntity);
            if (queryUser == null) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT, PushBackVo.class);
            }
            msg.setUser_id(queryUser.getUser_id());
        }
        msg.setCompany_id(notifyForm.getCompany_id());
        if(StringUtils.isNotEmpty(notifyForm.getTag())){
            msg.setTag(notifyForm.getTag());
        }
        msg.setCreate_time(new Date().getTime());
        msg.setMsg_title(notifyForm.getMessage_title());
        msg.setMsg_content(notifyForm.getContent());
        msg.setMsg_type(notifyForm.getMsg_type());
        if(notifyForm.getPush_time() != null){
            msg.setPush_time(notifyForm.getPush_time());
        }
        msgService.save(msg);

        PushBackVo backVo = new PushBackVo();
        return VOUtil.setSuccessResult(backVo);
	}

//    @Override
//    public void setAliasName(Long user_id, String company_id, String sendercomp_id) {
//        AppUser appUser = new AppUser(user_id, company_id, sendercomp_id,String.valueOf(user_id));
//        // 查询用户对应registration_id
//        AppUser user = this.queryUser(user_id, company_id,sendercomp_id);
//        if (user == null) {
//            // 新用户注册 添加绑定记录
//            appUserService.addAppUser(appUser);
//        }
//    }

    /**
     * 添加绑定用户记录-消息推送平台
     * @param appUser
     */
//    private void addAppUser(AppUser appUser) {
//        this.addAppUser(appUser);
//    }

    /**
     * 根据用户编号查询用户信息
     * @param appUserId
     * @return
     */
    private AppUser queryUser(long appUserId, String company_id, String senderCompId) {
        AppUser appUser = new AppUser(appUserId,company_id,senderCompId);
        return appUserService.getAppUser(appUser);
    }

    /**
     * 根据用户编号查询已绑定Tag
     * @param appUser
     * @return
     */
    private List<AppUserTags> queryTagsByUserId(AppUser appUser) {
        AppUserTags appUserTags = new AppUserTags(appUser.getApp_user_id(), appUser.getCompany_id(), appUser.getSendercomp_id());
        return appUserTagService.queryAppUserTag(appUserTags);
    }

    /**
     * 更新Alias、Tag
     * @param appUser
     * @param registrationId_new
     * @param terminal_type
     */
    private HSBCPSBackVO updateAliasAndTag(AppUser appUser, String registrationId_new,
                                                   String terminal_type, PushMsg pushMsg,String tags) {
        // 查询原registrationId 绑定tag(所有)
        String[] tag = tags.split(",");
//		// 查询原registrationId 取消绑定tag(无交叉关注)
//		Set<String> tags_remove = this.queryTagsByUserId(appUser, "3");
        HSBCPSBackVO result = null;
        try {
            if (tag != null && tag.length > 0) {
                // 清空和绑定分开，清空报错时，仍然进行绑定操作【zxpan 20150526】
                // 绑定AliasName或者Tag不为空时，删除极光服务器上当前账户关注的Tag
                UpdateDeviceTagAliasVo updateDeviceTagAliasVo = new UpdateDeviceTagAliasVo();
                updateDeviceTagAliasVo.setApp_key(pushMsg.getApp_key());
                updateDeviceTagAliasVo.setApp_secret(pushMsg.getApp_secret());
                updateDeviceTagAliasVo.setTags_add("");
                updateDeviceTagAliasVo.setTags_remove(tags);
                updateDeviceTagAliasVo.setRegistration_id(appUser.getRegistration_id());
                updateDeviceTagAliasVo.setAlias_name(appUser.getAlias_name());
                result = pushExtService.updateDeviceTagAlias(updateDeviceTagAliasVo);
            }
            if (tag != null && tag.length > 0) {
                // 为新的registrationId绑定Alias、Tag
                UpdateDeviceTagAliasVo updateDeviceTagAliasVo = new UpdateDeviceTagAliasVo();
                updateDeviceTagAliasVo.setApp_key(pushMsg.getApp_key());
                updateDeviceTagAliasVo.setApp_secret(pushMsg.getApp_secret());
                updateDeviceTagAliasVo.setTags_add(tags);
                updateDeviceTagAliasVo.setTags_remove("");
                updateDeviceTagAliasVo.setRegistration_id(appUser.getRegistration_id());
                updateDeviceTagAliasVo.setAlias_name(appUser.getAlias_name());
                result = pushExtService.updateDeviceTagAlias(updateDeviceTagAliasVo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        // 更新消息平台用户信息-更新极光注册ID
        this.updateAppUser(appUser.getApp_user_id(), registrationId_new,
                terminal_type, appUser.getCompany_id(), appUser.getSendercomp_id());
        return result;
    }

    /**
     * 设置Tag-消息推送平台
     * action_in：1-添加,2-修改，3-删除
     * @param appUserId
     * @param tag
     * @param action_in
     * @param sendercompId 接入渠道编号
     */
    private void setTag(long appUserId, String tag, String action_in,String company_id, String sendercompId) {
        AppUserTags appUserTags = new AppUserTags(appUserId,company_id,sendercompId,tag);
        List<AppUserTags> list = appUserTagService.queryAppUserTag(appUserTags);
        if("1".equals(action_in)){
            if(list == null || list.size() == 0){
                appUserTagService.addAppUserTags(appUserTags);
            }
        }else if("2".equals(action_in)){
//            appUserTagDAO.updateTag(appUserTags);
        }else if("3".equals(action_in)){
            if(list!=null && list.size()>0) {
                appUserTagService.deleteTag(appUserTags);
            }
        }
    }

    /**
     * 修改用户信息-消息推送平台
     * 更新极光注册ID
     * @param appUserId
     * @param registrationId_new
     * @param sendercompId
     */
    private void updateAppUser(long appUserId, String registrationId_new,
                               String terminal_type,String company_id, String sendercompId) {
        AppUser appUser = new AppUser(appUserId, registrationId_new,company_id, sendercompId,terminal_type);
        appUserService.updateAppUser(appUser);
    }

    /**
     * 获取极光推送appkey
     * @param company_id
     * @param senderComp_id
     * @return
     */
    private PushMsg getPushMsg(String company_id, String senderComp_id){
        PushMsg msg = new PushMsg(company_id, senderComp_id);
        return pushMsgService.getPushMsg(msg);
    }

    @Override
    public HSBCPSBackVO ennable_push(EnableDisableScheduleVo form) {
        PushMsg pushMsg = this.getPushMsg(form.getCompany_id(),form.getSendercomp_id());
        form.setApp_key(pushMsg.getApp_key());
        form.setApp_secret(pushMsg.getApp_secret());
        return pushExtService.enableSchedulePush(form);
    }

    @Override
    public HSBCPSBackVO disable_push(EnableDisableScheduleVo form) {
        PushMsg pushMsg = this.getPushMsg(form.getCompany_id(),form.getSendercomp_id());
        form.setApp_key(pushMsg.getApp_key());
        form.setApp_secret(pushMsg.getApp_secret());
        return pushExtService.disableSchedulePush(form);
    }

    @Override
    public HSBCPSBackVO update_push(UpdateScheduleVo form) {
        PushMsg pushMsg = this.getPushMsg(form.getCompany_id(),form.getSendercomp_id());
        form.setApp_key(pushMsg.getApp_key());
        form.setApp_secret(pushMsg.getApp_secret());
        return pushExtService.updateSchedulePush(form);
    }


    @Override
    public PushReportBack getPushReport(PushReportVo form) {
        PushMsg pushMsg = this.getPushMsg(form.getCompany_id(),form.getSendercomp_id());
        form.setApp_key(pushMsg.getApp_key());
        form.setApp_secret(pushMsg.getApp_secret());
        return pushExtService.getPushReport(form);
    }





    /**
     * 发送推送消息
     *  title 标题
     *  msgContent 通知内容
     *  tag 标签
     */
    @Override
    public PushBackVo bgsendPush(NotifyForm notifyForm) {
        PushMsg temp = new PushMsg();
        temp.setCompany_id(notifyForm.getCompany_id());
        temp.setSendercomp_id(notifyForm.getSendercomp_id());
        PushMsg pushMsg = pushMsgService.getPushMsg(temp);
        if (pushMsg == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_MSG_ERR, PushBackVo.class);
        }
        PushBack back = null;
        String mobile = "";
        String alias_name = "";
        String tag = "";
        Long user_id = null;
        //批量导入excel推送
        if (PushType.TAG.getVal().equals(notifyForm.getPush_type())) {
            // 按标签推送
            PushTagVo tagVo = new PushTagVo();
            tagVo.setApp_key(pushMsg.getApp_key());
            tagVo.setApp_secret(pushMsg.getApp_secret());
            tagVo.setMessage_title(notifyForm.getMessage_title());
            tagVo.setContent(notifyForm.getContent());
            tagVo.setTag(notifyForm.getTag());
            tagVo.setPush_time(notifyForm.getPush_time());
            back = pushExtService.sendAllNotificationWithTag(tagVo);
            tag = notifyForm.getTag();
        } else if (PushType.ALIAS.getVal().equals(notifyForm.getPush_type())) {
            // 按别名推送
            PushAliasVo pushAliasVo = new PushAliasVo();
            pushAliasVo.setApp_key(pushMsg.getApp_key());
            pushAliasVo.setApp_secret(pushMsg.getApp_secret());
            pushAliasVo.setMessage_title(notifyForm.getMessage_title());
            pushAliasVo.setContent(notifyForm.getContent());
            pushAliasVo.setAlias_name(notifyForm.getAlias_name());
            pushAliasVo.setPush_time(notifyForm.getPush_time());
            alias_name = notifyForm.getAlias_name();
            back = pushExtService.sendAllNotificationWithAlias(pushAliasVo);
        } else if (PushType.REGISTRATION_ID.getVal().equals(notifyForm.getPush_type())) {
            // 按设备编号推送
            UserEntity userEntity = new UserEntity();
            userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            notifyForm.setUser_id(null);
            userEntity.setUser_name(notifyForm.getMobile());
            userEntity.setSendercomp_id(notifyForm.getSendercomp_id());
            userEntity.setCompany_id(notifyForm.getCompany_id());
            UserEntity queryUser = userService.getUserEntity(userEntity);
            if (queryUser == null) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT, PushBackVo.class);
            }
            AppUser appUserTemp = new AppUser(queryUser.getUser_id(), queryUser.getCompany_id(), queryUser.getSendercomp_id());
            AppUser appUser = appUserService.getAppUser(appUserTemp);
            if (appUser == null) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_REGID_ERR, PushBackVo.class);
            }
            PushRegIdVo pushRegIdVo = new PushRegIdVo();
            pushRegIdVo.setRegistration_id(appUser.getRegistration_id());
            pushRegIdVo.setApp_key(pushMsg.getApp_key());
            pushRegIdVo.setApp_secret(pushMsg.getApp_secret());
            pushRegIdVo.setMessage_title(notifyForm.getMessage_title());
            pushRegIdVo.setContent(notifyForm.getContent());
            pushRegIdVo.setPush_time(notifyForm.getPush_time());
            back = pushExtService.sendAllNotificationWithRegId(pushRegIdVo);
            mobile = queryUser.getMobile();
            user_id = queryUser.getUser_id();
        } else if (PushType.ALL.getVal().equals(notifyForm.getPush_type())) {
            // 推送所有-广播
            PushAllVo pushAllVo = new PushAllVo();
            pushAllVo.setApp_key(pushMsg.getApp_key());
            pushAllVo.setApp_secret(pushMsg.getApp_secret());
            pushAllVo.setMessage_title(notifyForm.getMessage_title());
            pushAllVo.setContent(notifyForm.getContent());
            pushAllVo.setPush_time(notifyForm.getPush_time());
            back = pushExtService.sendNotificationAll(pushAllVo);
        } else {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_TYPE_ERR, PushBackVo.class);
        }
        boolean result = back == null ? false : VOUtil.isSuccess(back);
        if (!result) {
            return VOUtil.genErrorResult(back.getError_no(), back.getError_info(), PushBackVo.class);
        }

        if(PushModelType.COMBINE_UPDATE.getVal().equals(notifyForm.getPush_mode_type())) {
            //记录消息表
            Msg msg = new Msg();
            if (notifyForm.getUser_id()!=null) {
                UserEntity userEntity = new UserEntity();
                userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                userEntity.setUser_id(notifyForm.getUser_id());
                userEntity.setSendercomp_id(notifyForm.getSendercomp_id());
                userEntity.setCompany_id(notifyForm.getCompany_id());
                UserEntity queryUser = userService.getUserEntity(userEntity);
                if (queryUser == null) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT, PushBackVo.class);
                }
                msg.setUser_id(queryUser.getUser_id());
            }
            msg.setCompany_id(notifyForm.getCompany_id());
            if (StringUtils.isNotEmpty(notifyForm.getTag())) {
                msg.setTag(notifyForm.getTag());
            }
            msg.setCreate_time(new Date().getTime());
            msg.setMsg_title(notifyForm.getMessage_title());
            msg.setMsg_content(notifyForm.getContent());
            msg.setMsg_type(MsgType.COMBINE.getVal());
            msg.setCombine_code(notifyForm.getTag());
            if (notifyForm.getPush_time() != null) {
                msg.setPush_time(notifyForm.getPush_time());
            }
            msgService.save(msg);
        }
        PushBackVo backVo = new PushBackVo();
        return VOUtil.setSuccessResult(backVo);
    }

    /**
     * 西南添加tag绑定
     */
    @Override
    public TagsAddBackVo xinanTagsAdd(TagsAddForm tagsAddForm) {
        AppUser appUser = new AppUser(tagsAddForm.getUser_id(), tagsAddForm.getCompany_id(), tagsAddForm.getSendercomp_id());
        Set<String> tagSet = new HashSet<>();
        List<AppUserTags> list = this.queryTagsByUserId(appUser);
        for (AppUserTags t : list) {
            tagSet.add(t.getTag());
        }
        //已经存在tag  则不保存
        if(tagSet.contains(tagsAddForm.getTag())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.TAG_EXIST,
                    TagsAddBackVo.class);
        }
        this.setTag(tagsAddForm.getUser_id(), tagsAddForm.getTag(), "1",
                tagsAddForm.getCompany_id(), tagsAddForm.getSendercomp_id());
        return VOUtil.setSuccessResult(new TagsAddBackVo());
    }

    /**
     * 西南删除tag绑定
     */
    @Override
    public TagsRemoveBackVo xinanTagsDelete(TagsRemoveForm tagsRemoveForm) {
        AppUser appUser = new AppUser(tagsRemoveForm.getUser_id(), tagsRemoveForm.getCompany_id(), tagsRemoveForm.getSendercomp_id());
        Set<String> tagSet = new HashSet<>();
        List<AppUserTags> list = this.queryTagsByUserId(appUser);
        for (AppUserTags t : list) {
            tagSet.add(t.getTag());
        }
        //不存在标签
        if(!tagSet.contains(tagsRemoveForm.getTag())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.TAG_NOT_EXIST,
                    TagsRemoveBackVo.class);
        }
        // 设置消息平台 tag绑定关系
        this.setTag(tagsRemoveForm.getUser_id(),
                tagsRemoveForm.getTag(), "3", tagsRemoveForm.getCompany_id(), tagsRemoveForm.getSendercomp_id());
        return VOUtil.setSuccessResult(new TagsRemoveBackVo());
    }


    @Override
    public PushBackVo xinanTemplatePush(XinanPushForm xpf){
        //查询所有该标签的用户
        AppUserTags tempTags = new AppUserTags();
        tempTags.setTag(xpf.getTag());
        tempTags.setCompany_id(xpf.getCompany_id());
        List<AppUserTags> AppUserTagsList = appUserTagService.queryAppUserTag(tempTags);
        List<Long> userIdList = new ArrayList<>();
        for(AppUserTags appUserTags : AppUserTagsList){
            userIdList.add(appUserTags.getApp_user_id());
        }
        //查询用户提醒开关
        UserRemind userRemind = new UserRemind();
        userRemind.setCompany_id(xpf.getCompany_id());
        userRemind.setRemind_type(xpf.getUserRemindType().getVal());
        if(xpf.getUserRemindType() == UserRemindType.COMBINE){
            userRemind.setTag(xpf.getTag());
        }
        List<UserRemind> userRemindList = userRemindService.listRemind(userRemind);
        Map<String,UserRemind> map = new HashMap<>(userRemindList.size());
        for(UserRemind ur : userRemindList){
            if(ur.getTag() == null){
                map.put(ur.getUser_id().toString(), ur);
            }else{
                map.put(ur.getUser_id() + ur.getTag(), ur);
            }
        }
        //推送用户列表
        List<Long> idList = new ArrayList<>();
        for(Long userId : userIdList){
            String countRemind = userId.toString();//总开关
            String remind = userId + xpf.getTag();//分开关
            if(xpf.getUserRemindType() == UserRemindType.LEADER){
                if (map.get(countRemind) != null && map.get(countRemind).getFlag() == 1){
                    idList.add(userId);
                }
            }else{
                if (map.get(countRemind) != null && map.get(countRemind).getFlag() == 1
                        && map.get(remind) != null && map.get(remind).getFlag() == 1) {
                    idList.add(userId);
                }
            }
        }
        //推送用户列表为空
        if(idList.size() == 0){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_USER_LIST_EMPTY,PushBackVo.class);
        }
        List<UserEntity> userList = userService.getUserList(idList);
        List<String> openIdList = new ArrayList<>();
        for(UserEntity userEntity : userList){
            if(StringUtils.isNotEmpty(userEntity.getOpen_id())){
                openIdList.add(userEntity.getOpen_id());
            }
        }
        //推送openid列表为空
        if(openIdList.size() == 0){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_USER_OPEM_ID_LIST_EMPTY,PushBackVo.class);
        }
        CombDetailResult combDetailResult = new CombDetailResult();
        combDetailResult.setCombi_name("");
        if(xpf.getXinanPushType() != XinanPushType.VIEWPOINT){
            //查询组合基本信息
            CombDetailForm combDetailForm = new CombDetailForm();
            combDetailForm.setCombi_code(xpf.getTag());
            combDetailForm.setCompany_id(xpf.getCompany_id());
            combDetailForm.setSendercomp_id(xpf.getCompany_id());
            CombDetailQryBackVo combDetailQryBackVo = ledT2Service.func_comb_details(combDetailForm);
            if(VOUtil.isSuccess(combDetailQryBackVo)
                    && combDetailQryBackVo.getData_list()!=null
                    && combDetailQryBackVo.getData_list().size()>0){
                combDetailResult = combDetailQryBackVo.getData_list().get(0);
            }
        }
        Map<String,String> param = new HashMap<>(5);
        param.put("funcNo","1002900");
        param.put("weixinpk", ConfigUtil.get("weixin_pk","gh_4a5694efad94"));
        param.put("openidString", StringUtils.join(openIdList,","));
        param.put("url",ConfigUtil.get("template_url",""));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        if(xpf.getXinanPushType() == XinanPushType.VIEWPOINT){
            param.put("template_key",ConfigUtil.get("viewpoint_template_key","OPENTM207814132"));
            JSONObject paramJson = new JSONObject();
            paramJson.put("first","您的投顾发表新观点啦！");
            paramJson.put("keyword1",xpf.getViewpoint_theme());
            paramJson.put("keyword2",date);
            paramJson.put("remark","请及时关注");
            param.put("paramjson",paramJson.toString());
        }else if(xpf.getXinanPushType() == XinanPushType.COMBINE_UPDATE){
            param.put("template_key",ConfigUtil.get("combine_update_template_key","OPENTM405823082"));
            JSONObject paramJson = new JSONObject();
            paramJson.put("first","您的投顾进行了组合调仓，要及时跟进啊！");
            paramJson.put("keyword1",combDetailResult.getCombi_name());
            paramJson.put("keyword2",xpf.getContent());
            paramJson.put("keyword3",date);
            paramJson.put("remark","请及时关注");
            param.put("paramjson",paramJson.toString());
        }else if(xpf.getXinanPushType() == XinanPushType.COMBINE_APPLY_SUCCESS){
            param.put("template_key",ConfigUtil.get("combine_apply_success_template_key","OPENTM207814132"));
            JSONObject paramJson = new JSONObject();
            paramJson.put("first","您的投顾有新组合啦！");
            paramJson.put("keyword1",combDetailResult.getCombi_name());
            paramJson.put("keyword2",date);
            paramJson.put("remark","请及时关注");
            param.put("paramjson",paramJson.toString());
        }else if(xpf.getXinanPushType() == XinanPushType.COMBINE_CLOSE){
            param.put("template_key",ConfigUtil.get("combine_close_template_key","OPENTM408166684"));
            JSONObject paramJson = new JSONObject();
            paramJson.put("first","您的投顾关闭了组合，请知悉！");
            paramJson.put("keyword1",combDetailResult.getCombi_name());
            paramJson.put("keyword2",date);
            paramJson.put("remark","请及时关注");
            param.put("paramjson",paramJson.toString());
        }else{
            return VOUtil.setSuccessResult(new PushBackVo());
        }
        logger.debug(param.get("openidString"));
        String result = HttpClientUtil.sendGet(ConfigUtil.get("xinan_weixin_push_url", "https://wx.swsc.com.cn:8086/servlet/json"),
                param, HttpClientUtil.CHARSET, null, null, "西南微信推送");
        Map<String,String> resultMap = JSON.parseObject(result,Map.class);
        if(!"0".equals(resultMap.get("error_no"))){
            logger.error(resultMap.get("error_info"));
            return VOUtil.genErrorResult(resultMap.get("error_no"),resultMap.get("error_info"),PushBackVo.class);
        }
        return VOUtil.setSuccessResult(new PushBackVo());
    }

    public static void main(String[] args) {
        Map<String,String> param = new HashMap<String,String>(5);
        param.put("weixinpk","gh_4a5694efad94");
        param.put("funcNo","1002900");
        param.put("openidString", "oOIFkv6qtxn6legfcdS1WCVVVrPA");
        param.put("template_key","OPENTM405823082");
        param.put("url","baidu.com");
        JSONObject paramJson = new JSONObject();
        paramJson.put("first","您的投顾进行了组合调仓，要及时跟进啊！");
        paramJson.put("keyword1","名称名称");
        paramJson.put("keyword2","详情详情详情详情详情详情详情详情");
        paramJson.put("keyword3","2017-02-08 16:57:21");
        paramJson.put("remark","请及时关注");
        param.put("paramjson",paramJson.toString());
        String result = HttpClientUtil.sendGet(ConfigUtil.get("xinan_weixin_push_url", "https://wx.swsc.com.cn:8086/servlet/json"),
                param, HttpClientUtil.CHARSET, null, null, "西南微信推送");
        Map<String,String> resultMap = JSON.parseObject(result,Map.class);
        System.out.println(result);
    }

}
